using System;
using System.Collections.Generic;
using System.Linq;

namespace muduoDotNet.Common
{
    /// <summary>
    /// 通用工具类
    /// </summary>
    public static class Utils
    {
        /// <summary>
        /// 生成唯一ID
        /// </summary>
        /// <returns>唯一ID字符串</returns>
        public static string GenerateId()
        {
            return Guid.NewGuid().ToString("N");
        }

        /// <summary>
        /// 获取当前时间戳（毫秒）
        /// </summary>
        /// <returns>时间戳</returns>
        public static long GetCurrentTimestampMs()
        {
            return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
        }

        /// <summary>
        /// 格式化字节大小
        /// </summary>
        /// <param name="bytes">字节数</param>
        /// <returns>格式化后的字符串</returns>
        public static string FormatBytes(long bytes)
        {
            string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
            int suffixIndex = 0;
            double size = bytes;

            while (size >= 1024 && suffixIndex < suffixes.Length - 1)
            {
                size /= 1024;
                suffixIndex++;
            }

            return $"{size:F2} {suffixes[suffixIndex]}";
        }

        /// <summary>
        /// 安全执行操作，捕获并记录异常
        /// </summary>
        /// <param name="action">要执行的操作</param>
        /// <param name="errorMessage">错误消息</param>
        /// <returns>是否执行成功</returns>
        public static bool SafeExecute(Action action, string errorMessage = "操作执行失败")
        {
            try
            {
                action?.Invoke();
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error($"{errorMessage}: {ex.Message}", ex);
                return false;
            }
        }

        /// <summary>
        /// 安全执行操作，捕获并记录异常
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="func">要执行的函数</param>
        /// <param name="defaultValue">默认返回值</param>
        /// <param name="errorMessage">错误消息</param>
        /// <returns>执行结果或默认值</returns>
        public static T SafeExecute<T>(Func<T> func, T defaultValue = default(T), string errorMessage = "操作执行失败")
        {
            try
            {
                return func != null ? func() : defaultValue;
            }
            catch (Exception ex)
            {
                Logger.Error($"{errorMessage}: {ex.Message}", ex);
                return defaultValue;
            }
        }

        /// <summary>
        /// 判断集合是否为空或null
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="collection">集合</param>
        /// <returns>是否为空</returns>
        public static bool IsNullOrEmpty<T>(IEnumerable<T> collection)
        {
            return collection == null || !collection.Any();
        }
    }
}